import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Table, Row, Col, Tree, Divider,
  Popconfirm, Modal, Avatar, Icon, Tag,
} from 'antd';
import { isEmpty, isFunction, isObject, cloneDeep, findIndex, map, omit } from 'lodash';
import FileRenameDetail from './Details/File';
import FolderDetail from './Details/Folder';
import styles from './index.less';
import { recurAddKeyAndFileds, recursiveFind } from '/common/utils/ArrayUtils';
import { byte2KOM } from '/common/utils/numberUtils';
import PhotoSwiper from '/common/components/PhotoSwiper';
import { isImgByExt } from '/common/utils/imageUtils';
import ButtonComp from '/common/componentsTpl/ButtonComp';

@connect(({ global: { docList } }) => ({
  compData: docList,
}))
export default class FileCenterComp extends Component {

  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [], //选中的文件key
      selectedRows: [],//选中的文件objects
      selectedTreeKeys: [], //选中的目录
      renameVisible: false, //重命名弹框
      folderVisible: props.folderVisible, //编辑文件夹弹框
      renameObj: {},   //重命名信息
      refreshDoc: false, //是否刷新文件夹中的数据
      docUpdateComp: Math.ceil(Math.random() * 1000),
      docType: 1,  //编辑类型 1文件夹 2文件
      dirId: 0, //当前文件夹id
      editDir: {},
      isEdit: false,//文件夹是否未编辑状态
    };
    this.documentList = []; //文件信息
  }

  componentDidMount() {
    this.props.onRef && (this.props.onRef(this));
    this.fetchList();
  }

  /**
   * 凭证关联的附件
   */
  initFileCheck() {
    const { curFiles } = this.props;
    // console.log('stop2...');
    //已关联的文件
    if (curFiles && !isEmpty(curFiles)) {
      let selectedRowKeys = [], selectedRows = [];
      map(curFiles, (o) => {
        let tempInd = findIndex(this.documentList, (d) => {
          return d.saveName == o.saveName;
        });
        if (tempInd != -1) {
          selectedRowKeys.push(this.documentList[tempInd]['id']);
          selectedRows.push(this.documentList[tempInd]);
          this.documentList[tempInd]['isConnect'] = true;
        }
      });

      // console.log('this.documentList:',this.documentList);
      // this.setState({
      //   selectedRowKeys,
      //   selectedRows
      // },()=>{
      //   // this.triggerFileChange(selectedRowKeys,selectedRows);
      // });

    }
  }

  /**
   * 刷新文件夹信息
   * @param folderId
   */
  refreshFolder(folderId) {
    const { compData } = this.props;
    // console.log('step1..');
    this.documentList = [];
    if (compData && !isEmpty(compData)) {
      let list = cloneDeep(compData);
      let obj = recursiveFind(list, (obj) => {
        return obj.id == folderId;
      });
      if (!isEmpty(obj)) {
        this.documentList = obj.files;
      }
      this.initFileCheck();
    }
  }

  /**
   * 获取文件信息
   * @param payload
   */
  fetchList(payload = {}) {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/findDocList',
      payload: payload,
    });
  }

  /**
   * 删除文件
   * @param payload
   */
  deleteDoc(payload) {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/deleteDoc',
      payload: payload,
    }).then(rsp => {
      if (isObject(rsp) && (200 === rsp.status || 1 === rsp.status)) {
      }
    });
  }

  /**
   *创建文件夹
   * @param payload
   */
  createDoc(payload) {
    const { dispatch } = this.props;
    let $this = this;
    dispatch({
      type: 'global/createDoc',
      payload: payload,
    }).then(rsp => {
      if (isObject(rsp) && (200 === rsp.status || 1 === rsp.status)) {
        $this.hideDirModal();
      }
    });
  }

  /**
   *批量删除文件
   * @param payload
   */
  batchDelDoc(payload) {
    const { dispatch } = this.props;
    let $this = this;
    Modal.confirm({
      title: `批量删除${payload.type === 1 ? '文件夹' : '文件'}`,
      content: `您确定删除选中的${payload.type === 1 ? '文件夹' : '文件'}吗?`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'global/batchDelDoc',
          payload: payload,
        }).then(rsp => {
          if (isObject(rsp) && (200 === rsp.status || 1 === rsp.status)) {
            this.fetchList();
            if (payload.type === 2) {
              $this.setState({
                selectedRowKeys: [],
                selectedRows: [],
              }, () => {
                $this.onSelectChange([], []);
              });
            } else if (payload.type === 1) {
              $this.setState({
                selectedTreeKeys: [],
              }, () => {
                $this.props.onSelectDirChange && ($this.props.onSelectDirChange([]));
              });
            }

          }
        });
      },
    });

  }


  //显示重命名modal
  showRenameModal(record, docType, e) {
    e.stopPropagation();
    this.setState({
      renameVisible: true,
      renameObj: record,
      docType: docType,
    });
  }

  //隐藏重命名modal
  hideRenameModal() {
    this.setState({
      renameVisible: false,
    });
  }

  //modal确定重命名
  handleRename(payload) {
    const { dispatch } = this.props;
    if (!isEmpty(payload)) {
      payload['type'] = this.state.docType;
      dispatch({
        type: 'global/renameDoc',
        payload: payload,
      });
      if (2 === this.state.docType) {
        this.hideRenameModal();
      }
    }
  }

  //删除文件
  deleteFile(record) {
    this.deleteDoc({
      id: record.id,
      type: 2,
    });
  }

  initDocumentList() {
    const { dirId } = this.state;
    if (dirId > 0) {
      this.refreshFolder(dirId);
    }
  }

  /**
   * 获取目录文件
   * @param dirId
   */
  fetchFile(dirId) {
    // this.refreshFolder(dirId);
    this.setState({
      dirId: dirId,
      docUpdateComp: Math.ceil(Math.random() * 1000),
      refreshDoc: true,
    });
    // this.initFileCheck();
  }

  //选中的文件
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
    this.triggerFileChange(selectedRowKeys, selectedRows);
  };

  triggerFileChange(selectedRowKeys, selectedRows) {
    if (this.props.onSelectChange &&
      isFunction(this.props.onSelectChange)) {
      this.props.onSelectChange(selectedRowKeys, selectedRows);
    }
  }

  //清空选中文件
  clearSelectedRow() {
    this.setState({ selectedRowKeys: [], selectedRows: [] });
  }

  /**
   * 获取选中文件的ID
   * @returns {Array}
   */
  getSelectedRowKeys = () => {
    return this.state.selectedRowKeys;
  };

  /**
   * 获取选中文件的对象
   * @returns {Array}
   */
  getSelectedRows = () => {
    return this.state.selectedRows;
  };

  /**
   * 选中的文件夹
   * @param selectedTreeKeys
   */
  onSelect = (selectedTreeKeys, { selected: bool, selectedNodes, node, event }) => {

    this.fetchFile(selectedTreeKeys[0]);
    let $this = this;
    if (false == bool) {
      this.setState({
        selectedTreeKeys: [],
        editDir: {},
      }, () => {
        $this.triggerDirChange([]);
      });
    } else {
      let obj = recursiveFind([...this.props.compData], obj => {
        return node.props.dataId == obj.id;
      });
      this.setState({ selectedTreeKeys, editDir: obj }, () => {
        $this.triggerDirChange([obj.id]);
      });
    }
    this.setState({
      selectedRowKeys: [], //选中的文件key
      selectedRows: [],//选中的文件objects
    }, () => {
      $this.triggerFileChange([], []);
    });
  };

  //选中文件夹的回调
  triggerDirChange(value) {
    this.props.onSelectDirChange && (this.props.onSelectDirChange(value));
  }

  /**
   * 打开编辑文件夹弹框
   */
  showDirModal(isEdit = false) {
    this.setState({
      docType: 1,
      folderVisible: true,
      isEdit,
    });
  }

  hideDirModal() {
    this.setState({
      folderVisible: false,
    });
  }

  /**
   * 编辑文件夹
   * @param payload
   */
  saveDir(payload) {
    const { dispatch } = this.props;
    if (!isEmpty(payload)) {
      let $this = this, data = {
        id: payload.id,
        newName: payload.name,
        type: 1,
      };
      dispatch({
        type: 'global/renameDoc',
        payload: data,
      }).then(rsp => {
        if (isObject(rsp) && (200 === rsp.status || 1 === rsp.status)) {
          $this.hideDirModal();
        }
      });
    }
  }

  /**
   *初始化目录信息
   * **/
  dirTree(list) {
    if (isEmpty(list)) {
      return false;
    }
    const loop = data => data.map((item) => {
      if (item.children && item.children.length) {
        return <Tree.TreeNode key={item.id} dataId={item.id}
                              icon={({ expanded }) => (<Icon type={expanded ? 'folder-open' : 'folder'}/>)}
                              title={`${item.name}`}>{loop(item.children)} </Tree.TreeNode>;
      }
      return <Tree.TreeNode key={item.id}
                            dataId={item.id}
                            title={item.name}
                            icon={<Icon type={'folder'}/>}
      />;
    });

    return (
      <Tree
        showIcon={true}
        blockNode={true}
        defaultExpandAll
        onSelect={this.onSelect.bind(this)}
        onExpand={this.onExpand.bind(this)}
      >
        {loop(list)}
      </Tree>
    );
  }

  onExpand() {
    // console.log('..1!');
  }

  onClickFile(item, e) {
    e.stopPropagation();
    if (item.savePath && isImgByExt(item.ext)) {
      this.setState({ isShowPS: true, curFile: item });
    }
  }

  dealImgs() {

    if (isEmpty(this.documentList)) return [];

    return this.documentList
      .filter(v => (v && v.savePath && isImgByExt(v.ext)))
      .map(v => ({
        uid: v.saveName,
        name: v.name,
        src: v.savePath,
      }));
  }

  /**
   * 点击行选中
   * @param record
   * @param e
   */
  onClickRow(record, e) {
    e.stopPropagation();
    if ('TD' != e.target.nodeName) {
      return false;
    }
    if (typeof record.isConnect != 'undefined' && record.isConnect == true) {
      return false;
    }
    let tempKeys = [...this.state.selectedRowKeys],
      tempRows = [...this.state.selectedRows];
    let checkBoxInd = findIndex(tempKeys, (o) => {
      return o == record.id;
    });
    let newKeys = [...tempKeys], newRows = [...tempRows];
    //如果存在，则是反选
    if (checkBoxInd != -1) {
      newKeys = tempKeys.filter(item => item != tempKeys[checkBoxInd]);
      newRows = tempRows.filter(item => item.id != tempKeys[checkBoxInd]);
    } else {
      newKeys.push(record.id);
      newRows.push(record);
    }
    this.setState({
      selectedRowKeys: newKeys,
      selectedRows: newRows,
    });
    this.triggerFileChange(newKeys, newRows);
  }

  render() {
    const { selectedRowKeys, renameObj, docUpdateComp, isEdit } = this.state,
      { fileOper, compData, action } = this.props;
    this.initDocumentList();
    const layStyles = {
      height: this.props.treeHeight || document.body.offsetHeight - 220,
      border: '1px solid #e8e8e8',
      overflow: 'auto',
    };

    const tableProps = {
      key: docUpdateComp,
      className: `file-table-flex ${action ? 'bdt1' : ''}`,
      scroll: { y: layStyles.height - 35 - (action ? 50 : 0) },
      bordered: false,
      rowKey: 'id',
      rowSelection: {
        selectedRowKeys,
        onChange: this.onSelectChange,
        getCheckboxProps: record => ({
          disabled: typeof record.isConnect != 'undefined' ? record.isConnect : false,
        }),
        // selections:true
      },
      pagination: false,
      dataSource: this.documentList,
      onRow: (record) => {
        return {
          onClick: this.onClickRow.bind(this, record),
        };
      },
      style: {
        borderLeft: 'none',
      },
      columns: [
        {
          title: '文件名称',
          dataIndex: 'name',
          key: 'name',
          render: (text, record) => {
            const path = record.savePath ? record.savePath : '';
            return (
              <>
                <span
                  style={(typeof record.isConnect != 'undefined' && record.isConnect == true) ? { float: 'left' } : {}}>
                  {
                    (path && isImgByExt(record.ext)) ?
                      <Avatar onClick={this.onClickFile.bind(this, record)} shape={'square'} size={'large'} src={path}
                              alt={'图片'}/> :
                      <Avatar shape={'square'} size={'large'} icon={'file'}/>
                  }
                </span>

                <a style={{ display: 'inline-block' }} href="javascript:;" className={'pl8'}
                   onClick={this.onClickFile.bind(this, record)}>
                  <span style={{ display: 'inline-block', textOverflow: 'ellipsis', width: '150px' }}>{text}</span>
                  {
                    (typeof record.isConnect != 'undefined' && record.isConnect == true) &&
                    (
                      <span style={{ display: 'block' }}>
                          <Tag color="green">已关联</Tag>
                        </span>
                    )
                  }
                  {/*<span style={{display:'block'}}>{text}</span>*/}
                </a>
              </>
            );
          },
        },
        {
          title: '类型',
          dataIndex: 'ext',
          key: 'ext',
          width: '5%',
        },
        {
          title: '文件大小',
          dataIndex: 'size',
          key: 'size',
          width: '10%',
          render: (text, record) => {
            return byte2KOM(text);
          },
        },
        {
          title: '创建时间',
          dataIndex: 'updateTime',
          key: 'updateTime',
          width: '20%',
        },
      ],
    };
    if (fileOper) {
      tableProps['columns'].push({
        title: '操作',
        key: 'action',
        width: '25%',
        render: (text, record) => (
          <span style={{ fontSize: 15 }}>
            <a href={record.savePath} target="_blank" title={'下载'}><Icon type="download"/></a>
            <ButtonComp btnType={'a'} actionType={'rename'}
                        title={'重命名'}
                        onClick={this.showRenameModal.bind(this, record, 2)}>
              <Divider type="vertical"/><Icon type="edit"/></ButtonComp>
            <Popconfirm title="确认删除吗？" onConfirm={e => {
              e.stopPropagation();
              this.deleteFile(record);
            }} onCancel={e => {
              e.stopPropagation();
            }} okText="确认" cancelText="取消">
              <ButtonComp btnType={'a'} actionType={'deleteFile'}
                          title={'删除'}
                          onClick={e => {
                            e.stopPropagation();
                          }}>
                <Divider type="vertical"/><Icon className={'text-danger'} type="delete"/></ButtonComp>
            </Popconfirm>
          </span>
        ),
      });
    }

    const curFile = this.state.curFile;
    const photoList = this.dealImgs();
    const curPhotoInd = curFile && curFile.saveName ? findIndex(photoList, (v, k) => (v && v.uid === curFile.saveName)) : 0;

    let data = compData;
    return (
      <>
        <Row type="flex" gutter={8}>
          <Col span={6}>
            <div style={layStyles}>
              {this.dirTree(data)}
            </div>
          </Col>
          <Col span={18} className={styles.files}>
            <div style={layStyles}>
              {action}
              <div className={styles.dirPath}>path</div>
              <Table {...tableProps}/>
            </div>
          </Col>

          {data &&
          <FolderDetail dirComp={data}
                        compData={isEdit ? this.state.editDir : {}}
                        saveDetail={this.createDoc.bind(this)}
                        selectedDirKeys={this.state.selectedTreeKeys ? this.state.selectedTreeKeys : []}
                        hideDetail={this.props.hideDirModal.bind(this)}
                        isShowDetail={this.state.folderVisible}/>
          }
          <FileRenameDetail ref="fileRenameRefs"
                            compData={renameObj}
                            saveDetail={this.handleRename.bind(this)}
                            isShowDetail={this.state.renameVisible}
                            hideDetail={this.hideRenameModal.bind(this)}
          />
        </Row>
        {
          this.state.isShowPS && (
            <PhotoSwiper
              visible={this.state.isShowPS && photoList.length > 0}
              onClose={() => {
                this.setState({ isShowPS: false });
              }}
              curInd={curPhotoInd}
              photoList={photoList}
            />
          )
        }
      </>
    );
  }
}
FileCenterComp.defaultProps = {
  treeHeight: 0,
  fileOper: true,
  folderVisible: false,
  hideDirModal: () => {
  },
  action: null, // 文件列表上方的操作区域
  dirId: 0,//默认选中的文件夹
};
